package com.atguigu.ai.controller;

import com.atguigu.ai.constants.ChatTypeEnum;
import com.atguigu.ai.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.function.Consumer;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai/service")
public class ServiceController {
    private final ChatClient serviceChatClient;

    private final ChatHistoryRepository chatHistoryRepository;

    @GetMapping(produces = "text/html;charset=utf-8")
    public Flux<String> service(String prompt, String chatId) {
        chatHistoryRepository.save(ChatTypeEnum.service.name(), chatId);

        return serviceChatClient
                .prompt()
                .advisors(new Consumer<ChatClient.AdvisorSpec>() {
                    @Override
                    public void accept(ChatClient.AdvisorSpec advisorSpec) {
                        advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId);
                    }
                })
                .user(prompt)
                .stream()
                .content();

    }
}
